package pers.cj.pdos.controller;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.cj.pdos.controller.base.BaseController;

import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.controller.entity.ResponseEntity;
import pers.cj.pdos.controller.entity.ResponseList;
import pers.cj.pdos.entity.Company;
import pers.cj.pdos.entity.Custom;
import pers.cj.pdos.entity.Provider;
import pers.cj.pdos.service.IProviderService;
import pers.cj.pdos.utils.DataUtil;
import pers.cj.pdos.utils.PdosUtils;
import pers.cj.pdos.utils.Utils;
import pers.cj.pdos.vo.DataMsg;
import pers.cj.pdos.vo.ProviderVo;
import pers.cj.pdos.vo.UserVo;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenj
 * @since 2019-12-12
 */
@Controller
@RequestMapping("/provider")
public class ProviderController extends BaseController {
    @Autowired
    IProviderService providerService;

    @RequestMapping("/provider")
    @RequiresPermissions("provider:query")
    public String customType() {
        return "/provider/provider";
    }

    @RequestMapping("/providerNew")
    @RequiresPermissions("provider:insert")
    public String customNew() {
        return "/provider/providerNew";
    }

    @RequestMapping("/providerEdit")
    @RequiresPermissions("provider:insert")
    public String customEdit(Model model, String id) {
        model.addAttribute("id",id);
        return "/provider/providerEdit";
    }

    @ResponseBody
    @RequestMapping("/provider/getList")
    public ResponseList getList(int page,
                                int limit,
                                String status,
                                String search,
                                String providerTypeId,
                                String no,
                                String name,
                                String unitTel,
                                String phone,
                                String contacts,
                                String remark) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<ProviderVo> providerVoList = providerService.listVoPage(company.getId(),
                page,
                limit,
                Utils.genInteger(status),
                Utils.genLikeData(search),
                providerTypeId,
                Utils.genLikeData(no),
                Utils.genLikeData(name),
                Utils.genLikeData(unitTel),
                Utils.genLikeData(phone),
                Utils.genLikeData(contacts),
                Utils.genLikeData(remark),
                PdosUtils.getProviderStoreId(userVo,null));
        long count = providerService.count(company.getId(),
                Utils.genInteger(status),
                Utils.genLikeData(search),
                providerTypeId,
                Utils.genLikeData(no),
                Utils.genLikeData(name),
                Utils.genLikeData(unitTel),
                Utils.genLikeData(phone),
                Utils.genLikeData(contacts),
                Utils.genLikeData(remark),
                PdosUtils.getProviderStoreId(userVo,null));
        return ResponseList.success(count,providerVoList);
    }

    @ResponseBody
    @RequiresPermissions("provider:insert")
    @RequestMapping("/provider/add")
    public ResponseEntity add(@RequestBody Provider provider) {
        if (Utils.isEmpty(provider.getName())){
            return ResponseEntity.fail("客户名称不能为空");
        }
        if (Utils.isEmpty(provider.getNo())){
            return ResponseEntity.fail("客户编号不能为空");
        }
        if (Utils.isEmpty(provider.getStoreId())){
            return ResponseEntity.fail("门店不能为空");
        }
        if (Utils.isEmpty(provider.getProviderTypeId())){
            return ResponseEntity.fail("分类不能为空");
        }

        Company company = getCompany();

        if (providerService.checkName(company.getId(), provider.getName())) {
            return ResponseEntity.fail("客户名称已存在");
        }

        if (providerService.checkNo(company.getId(), provider.getNo())) {
            return ResponseEntity.fail("客户编号已存在");
        }
        DataUtil.processEntity(company, provider);

        if (provider.getInitAmt() == null) {
            provider.setInitAmt(new BigDecimal(0));
        }
        providerService.save(provider);
        return ResponseEntity.success();
    }

    @ResponseBody
    @RequiresPermissions("provider:insert")
    @RequestMapping("/provider/update")
    public ResponseEntity update(@RequestBody Provider provider) {
        if (Utils.isEmpty(provider.getName())){
            return ResponseEntity.fail("名称不能为空");
        }
        if (Utils.isEmpty(provider.getNo())){
            return ResponseEntity.fail("编号不能为空");
        }
        if (Utils.isEmpty(provider.getStoreId())){
            return ResponseEntity.fail("门店不能为空");
        }
        if (Utils.isEmpty(provider.getProviderTypeId())){
            return ResponseEntity.fail("分类不能为空");
        }

        Company company = getCompany();
        Provider old = providerService.getById(provider.getId());
        if (!old.getName().equals(provider.getName()) && providerService.checkName(company.getId(), provider.getName())) {
            return ResponseEntity.fail("名称已存在");
        }

        if (!old.getNo().equals(provider.getNo()) && providerService.checkNo(company.getId(), provider.getNo())) {
            return ResponseEntity.fail("编号已存在");
        }

        DataUtil.processEntity(false, company, provider);
        if (provider.getInitAmt() == null) {
            provider.setInitAmt(new BigDecimal(0));
        }
        providerService.update(provider);
        return ResponseEntity.success();
    }

    @ResponseBody
    @RequiresPermissions("provider:insert")
    @RequestMapping("/provider/delete")
    public ResponseEntity delete(@RequestBody Provider provider) {
        try{
            providerService.removeById(provider.getId());
            return ResponseEntity.success();
        } catch (Exception e) {
            return ResponseEntity.fail("已被使用无法删除");
        }
    }

    @ResponseBody
    @RequiresPermissions("provider:insert")
    @RequestMapping("/provider/batchChangeType")
    public ResponseEntity batchChangeType(String providerTypeId, @RequestBody List<Provider> list) {
        providerService.batchChangeType(providerTypeId, list);
        return ResponseEntity.success();
    }

    @ResponseBody
    @RequiresPermissions("provider:insert")
    @RequestMapping("/provider/batchDelete")
    public ResponseData batchDelete(@RequestBody List<Provider> list) {

        //判断哪些商品被单据引用了
        Map<String,Long> map = providerService.check(list);

        List<DataMsg> notDeleteList = new ArrayList<>();
        List<Provider> deleteList = new ArrayList<>();
        for (int i=0;i<list.size();i++){
            Provider provider = list.get(i);
            if(map.containsKey(provider.getId()) && map.get(provider.getId()) > 0) {
                //当该商品的被单据引用，则从列表中剔除该商品
                notDeleteList.add(new DataMsg(provider,"被业务单据引用"));
                continue;
            }
            deleteList.add(provider);
        }

        Collection<Provider> collection = providerService.listByIds(DataUtil.genIds(list));
        for (Provider provider:collection){
            if(map.containsKey(provider.getId()) && map.get(provider.getId()) > 0) {
                //当该商品的被单据引用，则从列表中剔除该商品
                notDeleteList.add(new DataMsg(provider,"被业务单据引用"));
                continue;
            }
            deleteList.add(provider);
        }

        ResponseData responseData;
        if (notDeleteList.size() > 0) {
            responseData = new ResponseData();
            responseData.setCode(3);
            responseData.setMsg("部分商品被单据引用");
            responseData.setData(notDeleteList);
        } else {
            responseData = ResponseData.success(null);
        }

        if (Utils.isEmpty(deleteList)){
            return responseData;
        }

        try {
            providerService.deleteBatch(deleteList);
            return responseData;
        } catch (Exception e){
            return ResponseData.fail("删除失败");
        }
    }

    @ResponseBody
    @RequestMapping("/provider/checkName")
    public ResponseEntity checkName(String name) throws UnsupportedEncodingException {
        Company company = getCompany();
        boolean exist = providerService.checkName(company.getId(), URLDecoder.decode(name,"UTF-8"));

        return exist ?  new ResponseEntity(1,"已被使用") : new ResponseEntity(2,"未被使用");
    }

    @ResponseBody
    @RequestMapping("/provider/getById")
    public ResponseData getById(String id) {
        if (Utils.isEmpty(id)) {
            return ResponseData.fail("id不能为空");
        }
        Provider provider = providerService.getById(id);
        if (provider == null ) {
            return ResponseData.fail("未找到客户");
        }
        return ResponseData.success(provider);
    }

    @ResponseBody
    @RequestMapping("/provider/getAll")
    public ResponseData getAll() {
        return ResponseData.success(providerService.listVo(getCompany().getId()));
    }


    @ResponseBody
    @RequestMapping("/provider/getDefault")
    public ResponseData getDefault() {
        Provider provider = providerService.getDefault(getLoginUserVo().getStoreId());
        return provider==null ? ResponseData.fail("暂无默认供应商"): ResponseData.success(provider);
    }
}
